<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-semibold text-gray-800">设备申请</h2>
      <button @click="$router.push('/equipment-application/form')" class="flex items-center px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
        <PlusIcon class="h-5 w-5 mr-2" />
        新建申请
      </button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
      <form @submit.prevent="handleSearch" class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label for="name" class="block text-sm font-medium text-gray-700">设备名称</label>
          <input type="text" id="name" v-model="searchForm.name" placeholder="请输入设备名称" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
        </div>
        <div>
          <label for="category" class="block text-sm font-medium text-gray-700">设备类别</label>
          <select id="category" v-model="searchForm.category" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <option value="">请选择类别</option>
            <option value="计算机设备">计算机设备</option>
            <option value="实验仪器">实验仪器</option>
            <option value="化学仪器">化学仪器</option>
            <option value="生物仪器">生物仪器</option>
            <option value="其他设备">其他设备</option>
          </select>
        </div>
        <div>
          <label for="status" class="block text-sm font-medium text-gray-700">申请状态</label>
          <select id="status" v-model="searchForm.status" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <option value="">请选择状态</option>
            <option value="PENDING">待审批</option>
            <option value="APPROVED">已批准</option>
            <option value="REJECTED">已拒绝</option>
            <option value="PURCHASED">已购买</option>
          </select>
        </div>
        <div>
          <label for="urgency" class="block text-sm font-medium text-gray-700">紧急程度</label>
          <select id="urgency" v-model="searchForm.urgency" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <option value="">请选择紧急程度</option>
            <option value="LOW">低</option>
            <option value="MEDIUM">中</option>
            <option value="HIGH">高</option>
          </select>
        </div>
        <div class="md:col-span-4 flex justify-end space-x-3 mt-4">
          <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">搜索</button>
          <button type="button" @click="handleReset" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">重置</button>
        </div>
      </form>
    </div>

    <!-- 申请列表 -->
    <div class="bg-white rounded-xl shadow-lg p-6">
      <div v-if="loading" class="text-center py-8">
        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600"></div>
        <p class="mt-2 text-gray-500">加载中...</p>
      </div>
      <div v-else class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">设备名称</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">设备类别</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">申请数量</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">预估单价</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">紧急程度</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">申请时间</th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="application in applications" :key="application.id">
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ application.name }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ application.category }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ application.quantity }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">¥{{ application.unitPrice }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm">
                <span :class="['px-2 inline-flex text-xs leading-5 font-semibold rounded-full', getUrgencyClass(application.urgency)]">
                  {{ getUrgencyText(application.urgency) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm">
                <span :class="['px-2 inline-flex text-xs leading-5 font-semibold rounded-full', getStatusClass(application.status)]">
                  {{ getStatusText(application.status) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ application.createTime }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button @click="viewDetail(application)" class="text-indigo-600 hover:text-indigo-900 mr-3">查看</button>
                <button @click="editApplication(application)" v-if="application.status === 'PENDING'" class="text-indigo-600 hover:text-indigo-900 mr-3">编辑</button>
                <button @click="approveApplication(application)" v-if="application.status === 'PENDING' && hasApprovalPermission()" class="text-green-600 hover:text-green-900 mr-3">批准</button>
                <button @click="rejectApplication(application)" v-if="application.status === 'PENDING' && hasApprovalPermission()" class="text-red-600 hover:text-red-900">拒绝</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="flex justify-end mt-6">
        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
          <button @click="handleCurrentChange(pagination.current - 1)" :disabled="pagination.current === 1" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
            <span class="sr-only">Previous</span>
            <ChevronLeftIcon class="h-5 w-5" aria-hidden="true" />
          </button>
          <button v-for="page in totalPages" :key="page" @click="handleCurrentChange(page)" :class="['relative inline-flex items-center px-4 py-2 border text-sm font-medium', page === pagination.current ? 'z-10 bg-indigo-50 border-indigo-500 text-indigo-600' : 'bg-white border-gray-300 text-gray-700 hover:bg-gray-50']">
            {{ page }}
          </button>
          <button @click="handleCurrentChange(pagination.current + 1)" :disabled="pagination.current === totalPages" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
            <span class="sr-only">Next</span>
            <ChevronRightIcon class="h-5 w-5" aria-hidden="true" />
          </button>
        </nav>
        <div class="ml-4 flex items-center text-sm text-gray-700">
          <span>共 {{ pagination.total }} 条</span>
          <select v-model="pagination.size" @change="handleSizeChange($event.target.value)" class="ml-2 block w-auto pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md">
            <option :value="10">10 条/页</option>
            <option :value="20">20 条/页</option>
            <option :value="50">50 条/页</option>
            <option :value="100">100 条/页</option>
          </select>
        </div>
      </div>
    </div>

    <!-- 批准申请对话框 -->
    <div v-if="showApprovalDialog" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
      <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div class="mt-3">
          <h3 class="text-lg font-medium text-gray-900 mb-4">审批申请</h3>
          <div class="mb-4">
            <p class="text-sm text-gray-600 mb-2">设备名称：{{ currentApplication?.name }}</p>
            <p class="text-sm text-gray-600 mb-2">申请数量：{{ currentApplication?.quantity }}</p>
            <p class="text-sm text-gray-600 mb-2">预估单价：¥{{ currentApplication?.unitPrice }}</p>
          </div>
          <div class="mb-4">
            <label for="approvalComment" class="block text-sm font-medium text-gray-700 mb-2">审批意见</label>
            <textarea
              id="approvalComment"
              v-model="approvalForm.comment"
              rows="3"
              class="w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              placeholder="请输入审批意见（可选）"
            ></textarea>
          </div>
          <div class="flex justify-end space-x-3">
            <button @click="cancelApproval" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">
              取消
            </button>
            <button @click="confirmApproval" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2">
              确认批准
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 拒绝申请对话框 -->
    <div v-if="showRejectDialog" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
      <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div class="mt-3">
          <h3 class="text-lg font-medium text-gray-900 mb-4">拒绝申请</h3>
          <div class="mb-4">
            <p class="text-sm text-gray-600 mb-2">设备名称：{{ currentApplication?.name }}</p>
            <p class="text-sm text-gray-600 mb-2">申请数量：{{ currentApplication?.quantity }}</p>
            <p class="text-sm text-gray-600 mb-2">预估单价：¥{{ currentApplication?.unitPrice }}</p>
          </div>
          <div class="mb-4">
            <label for="rejectComment" class="block text-sm font-medium text-gray-700 mb-2">拒绝原因 *</label>
            <textarea
              id="rejectComment"
              v-model="rejectForm.comment"
              rows="3"
              required
              class="w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              placeholder="请输入拒绝原因"
            ></textarea>
          </div>
          <div class="flex justify-end space-x-3">
            <button @click="cancelReject" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">
              取消
            </button>
            <button @click="confirmReject" class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2">
              确认拒绝
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { PlusIcon, ChevronLeftIcon, ChevronRightIcon } from '@heroicons/vue/24/outline'
import request from '@/utils/request'
import { hasApprovalPermission } from '@/utils/permission'

const router = useRouter()

const applications = ref([])
const loading = ref(false)

const searchForm = reactive({
  name: '',
  category: '',
  status: '',
  urgency: ''
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const totalPages = computed(() => Math.ceil(pagination.total / pagination.size))

// 批准和拒绝申请相关变量
const showApprovalDialog = ref(false)
const showRejectDialog = ref(false)
const currentApplication = ref(null)

const approvalForm = reactive({
  comment: ''
})

const rejectForm = reactive({
  comment: ''
})

// 获取状态样式
const getStatusClass = (status) => {
  const statusMap = {
    'PENDING': 'bg-yellow-100 text-yellow-800',
    'APPROVED': 'bg-green-100 text-green-800',
    'REJECTED': 'bg-red-100 text-red-800',
    'PURCHASED': 'bg-blue-100 text-blue-800'
  }
  return statusMap[status] || 'bg-gray-100 text-gray-800'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'PENDING': '待审批',
    'APPROVED': '已批准',
    'REJECTED': '已拒绝',
    'PURCHASED': '已购买'
  }
  return statusMap[status] || status
}

// 获取紧急程度样式
const getUrgencyClass = (urgency) => {
  const urgencyMap = {
    'LOW': 'bg-blue-100 text-blue-800',
    'MEDIUM': 'bg-yellow-100 text-yellow-800',
    'HIGH': 'bg-red-100 text-red-800'
  }
  return urgencyMap[urgency] || 'bg-gray-100 text-gray-800'
}

// 获取紧急程度文本
const getUrgencyText = (urgency) => {
  const urgencyMap = {
    'LOW': '低',
    'MEDIUM': '中',
    'HIGH': '高'
  }
  return urgencyMap[urgency] || urgency
}

// 查看详情
const viewDetail = (application) => {
  router.push(`/equipment-application/${application.id}`)
}

// 编辑申请
const editApplication = (application) => {
  router.push(`/equipment-application/form/${application.id}`)
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadApplications()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    category: '',
    status: '',
    urgency: ''
  })
  pagination.current = 1
  loadApplications()
}

// 页面大小改变
const handleSizeChange = (size) => {
  pagination.size = parseInt(size)
  pagination.current = 1
  loadApplications()
}

// 当前页改变
const handleCurrentChange = (current) => {
  if (current < 1 || current > totalPages.value) return
  pagination.current = current
  loadApplications()
}

// 加载申请列表
const loadApplications = async () => {
  try {
    loading.value = true
    
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      equipmentName: searchForm.name || undefined,
      equipmentCategory: searchForm.category || undefined,
      status: searchForm.status || undefined,
      urgency: searchForm.urgency || undefined
    }

    const response = await request.get('/equipment-application/list', { params })
    applications.value = response.data.records.map(app => ({
      id: app.id,
      name: app.equipmentName,
      category: app.category,
      quantity: app.quantity,
      unitPrice: app.estimatedPrice,
      urgency: app.urgency,
      status: app.status,
      createTime: app.createTime
    }))
    pagination.total = response.data.total
    
  } catch (error) {
    console.error('加载申请列表失败:', error)
    showMessage('加载申请列表失败', 'error')
  } finally {
    loading.value = false
  }
}

// 简单消息显示函数
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

// 批准申请
const approveApplication = (application) => {
  currentApplication.value = application
  approvalForm.comment = ''
  showApprovalDialog.value = true
}

// 拒绝申请
const rejectApplication = (application) => {
  currentApplication.value = application
  rejectForm.comment = ''
  showRejectDialog.value = true
}

// 取消批准
const cancelApproval = () => {
  showApprovalDialog.value = false
  currentApplication.value = null
  approvalForm.comment = ''
}

// 取消拒绝
const cancelReject = () => {
  showRejectDialog.value = false
  currentApplication.value = null
  rejectForm.comment = ''
}

// 确认批准
const confirmApproval = async () => {
  try {
    const requestData = {
      applicationId: currentApplication.value.id,
      status: 'APPROVED',
      approvalDate: new Date().toISOString().split('T')[0],
      approvalComment: approvalForm.comment || null
    }

    await request.post(`/equipment-application/${currentApplication.value.id}/approve`, requestData)
    showMessage('申请批准成功', 'success')
    showApprovalDialog.value = false
    currentApplication.value = null
    approvalForm.comment = ''
    loadApplications() // 重新加载列表
  } catch (error) {
    console.error('批准申请失败:', error)
    showMessage('批准申请失败', 'error')
  }
}

// 确认拒绝
const confirmReject = async () => {
  if (!rejectForm.comment.trim()) {
    showMessage('请输入拒绝原因', 'warning')
    return
  }

  try {
    const requestData = {
      applicationId: currentApplication.value.id,
      status: 'REJECTED',
      approvalDate: new Date().toISOString().split('T')[0],
      approvalComment: rejectForm.comment
    }

    await request.post(`/equipment-application/${currentApplication.value.id}/approve`, requestData)
    showMessage('申请拒绝成功', 'success')
    showRejectDialog.value = false
    currentApplication.value = null
    rejectForm.comment = ''
    loadApplications() // 重新加载列表
  } catch (error) {
    console.error('拒绝申请失败:', error)
    showMessage('拒绝申请失败', 'error')
  }
}

onMounted(() => {
  loadApplications()
})
</script>